import traceback

import requests
from loguru import logger

logger.add("/var/log/Task/sdwan_api/sdwan_api.log", rotation="00:00", backtrace=True,
           diagnose=True, level="DEBUG")


def get_host_config(sdwan_url, username, password, hostname):
    try:
        url = f"{sdwan_url}/vnms/appliance/export?applianceName={hostname}&export-as-plain-text=false"
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'text/plain'
        }
        req = requests.get(url=url, auth=(username, password), headers=headers, verify=False)
        if req.status_code != 200 or not req.text:
            sdwan_response = {'status': 'fail', 'data': f"{hostname}获取SDWAN配置失败"}
            logger.error(f"{hostname}获取SDWAN配置失败：状态码:{req.status_code}, 配置数据:{req.text}")
        else:
            logger.info(f"{hostname}获取SDWAN配置成功：状态码:{req.status_code}")
            sdwan_response = {"status": 'success', 'data': req.text}
    except Exception:
        logger.error(traceback.format_exc())
        sdwan_response = {'status': 'fail', 'data': traceback.format_exc()}
    return sdwan_response

